package cn.hengzhu.main_manager.web.controller;

import cn.hengzhu.main_manager.repository.dao.*;
import cn.hengzhu.main_manager.repository.domain.*;
import cn.hengzhu.main_manager.repository.vo.*;
import cn.hengzhu.main_manager.utils.DateTimeHelper;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.MoblieUrl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;


@Controller
public class PageController {

	@Autowired
	private ManageRolesMapper manageRolesMapper;
	@Autowired
	private ManageCompMapper manageCompMapper;
	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private ManageCaseBoxMapper manageCaseBoxMapper;
	@Autowired
	private AccessRecordMapper accessRecordMapper;
	@Autowired
	private ManageCaseTypeMapper manageCaseTypeMapper;

	@Autowired
	private HttpServletRequest request;


	//登录跳转
	@MoblieUrl
	@RequestMapping("/login/index")
	public String login(HttpServletRequest request) {
		return request.getAttribute("moblie") + "login";
	}

	//柜子列表
	@MoblieUrl
	@RequestMapping("/stateList/index")
	public String stateList(Model model, HttpServletRequest request) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		List<ManageCase> selectByExample = new ArrayList<>();
		ManageCaseExample mce = new ManageCaseExample();
		if (compId.equals(0)) {
			selectByExample = manageCaseMapper.selectByExample(mce);
			List<ManageComp> compList = manageCompMapper.selectByExample(new ManageCompExample());
			model.addAttribute("comps", compList);
		} else {
			mce.createCriteria().andCompIdEqualTo(compId);//公司id
			selectByExample = manageCaseMapper.selectByExample(mce);
		}
		model.addAttribute("compId", compId);
		if (!selectByExample.isEmpty()) {
			Map<Byte, Long> collect = selectByExample.stream().collect(Collectors.groupingBy(ManageCase::getUseType, Collectors.counting()));
			List<CaseUseTypeVO> TypeList = new ArrayList<>();
			collect.forEach((k, v) -> {
				CaseUseTypeVO c = new CaseUseTypeVO();
				c.setKindId(k.intValue());
				c.setNum(v.intValue());
				if (k == 1) {
					c.setKindName("普通储物柜");
				} else if (k == 2) {
					c.setKindName("医用床");
				} else if (k == 3) {
					c.setKindName("快递柜");
				} else if (k == 4) {
					c.setKindName("快餐");
				} else if (k == 5) {
					c.setKindName("成人用品柜");
				} else if (k == 6) {
					c.setKindName("智能医药柜");
				} else if (k == 7) {
					c.setKindName("自动柜");
				}
				TypeList.add(c);
			});

			int sum = TypeList.stream().mapToInt(CaseUseTypeVO::getNum).sum();

			CaseUseTypeVO c = new CaseUseTypeVO();
			c.setKindId(0);
			c.setKindName("全部");
			c.setNum(sum);
			TypeList.add(0, c);

			model.addAttribute("type", TypeList);
		}
		return request.getAttribute("moblie") + "stateList";
	}


	//柜子详情
	@MoblieUrl
	@RequestMapping("/stateDetails/index")
	public String stateEdit(Model model, String caseNo) {
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		List<ManageComp> compList = new ArrayList<>();
		List<ManageCaseType> caseTypeList = new ArrayList<>();
		if (StringUtils.isNotBlank(caseNo)) {


			ManageCaseExample example = new ManageCaseExample();

			example.createCriteria().andCaseNoEqualTo(caseNo);
			List<ManageCase> selectByExample = manageCaseMapper.selectByExample(example);
			ManageCase caseByCaseNo = selectByExample.get(0);
			Integer ownCompId = caseByCaseNo.getCompId();
			Integer ownTypeId = caseByCaseNo.getTypeId();
			Byte useType = caseByCaseNo.getUseType();
			Byte isSize = caseByCaseNo.getIsSize();
			if (ownCompId != null) {// 已有所属公司
				//查询公司列表
				List<ManageComp> list = manageCompMapper.getCompListBySelect(compId);
				list.stream().forEach(a -> {
					ManageComp manageComp = new ManageComp();
					manageComp.setCompName(a.getCompName());
					manageComp.setCompId(a.getCompId());
					if (a.getCompId().equals(ownCompId)) {
						compList.add(0, manageComp);
					} else {
						compList.add(manageComp);
					}
				});
				//查询已有公司对应的，，收费类型列表
				ManageCaseTypeExample caseTypeExample = new ManageCaseTypeExample();
				caseTypeExample.createCriteria().andCompIdEqualTo(ownCompId);
				List<ManageCaseType> getCaseTypeList = manageCaseTypeMapper.selectByExample(caseTypeExample);
				getCaseTypeList.stream().forEach(a -> {
					ManageCaseType manageCaseType = new ManageCaseType();
					manageCaseType.setTypeId(a.getTypeId());
					manageCaseType.setName(a.getName());
					if (a.getTypeId().equals(ownTypeId)) {
						caseTypeList.add(0, manageCaseType);
					} else {
						caseTypeList.add(manageCaseType);
					}
				});
				model.addAttribute("myCompList", compList);
				model.addAttribute("caseTypeList", caseTypeList);
				model.addAttribute("useType", useType);
				model.addAttribute("isSize", isSize);
			} else {

				List<ManageComp> list = manageCompMapper.getCompListBySelect(compId);
				list.stream().forEach(a -> {
					ManageComp manageComp = new ManageComp();
					manageComp.setCompName(a.getCompName());
					manageComp.setCompId(a.getCompId());
					compList.add(manageComp);
				});
				ManageComp manageComp = new ManageComp();
				manageComp.setCompId(null);
				manageComp.setCompName("--请选择--");
				compList.add(0, manageComp);
				model.addAttribute("myCompList", compList);
				model.addAttribute("useType", useType);
				model.addAttribute("isSize", isSize);
				
			}


		} else {
			List<ManageComp> list = manageCompMapper.getCompListBySelect(compId);
			list.stream().forEach(a -> {
				ManageComp manageComp = new ManageComp();
				manageComp.setCompName(a.getCompName());
				manageComp.setCompId(a.getCompId());
				compList.add(manageComp);
			});
			ManageComp manageComp = new ManageComp();
			manageComp.setCompId(null);
			manageComp.setCompName("--请选择--");
			compList.add(0, manageComp);
			model.addAttribute("myCompList", compList);
		}
		return request.getAttribute("moblie") + "stateEdit";
	}

	//箱子使用记录
	@MoblieUrl
	@RequestMapping("/stateRecord/index")
	public String stateRecord() {
		System.out.println(request.getAttribute("moblie") + "============");
		return request.getAttribute("moblie") + "stateRecord";
	}

	//管理员列表
	@MoblieUrl
	@RequestMapping("/myUser/index")
	public String manager() {
		return request.getAttribute("moblie") + "adminList";
	}

	//管理员的编辑
	@MoblieUrl
	@RequestMapping("/managerEdit/index")
	public String managerEdit(Model model, Integer roleId) {
		ManageUser user = UserContext.getUser();
		Integer ownRoleId = user.getRoleId();
		ManageRoles ownManageRoles = manageRolesMapper.selectByPrimaryKey(ownRoleId);
		List<String> ownPermssionList = Arrays.asList(ownManageRoles.getPermissions().split(","));
		//所选的角色Id
		ManageRoles permssionByRoleId = manageRolesMapper.selectByPrimaryKey(roleId);

		Integer compId = permssionByRoleId.getCompId();
		List<RoleVO> ownRoleList = new ArrayList<>();

		ManageRolesExample example = new ManageRolesExample();
		example.createCriteria().andCompIdEqualTo(compId);
		List<ManageRoles> roleList = manageRolesMapper.selectByExample(example);
		roleList.stream().forEach(b -> {
			List<String> otherPermssionList = Arrays.asList(b.getPermissions().split(","));
			if (ownPermssionList.containsAll(otherPermssionList)) {
				RoleVO roleVO = new RoleVO();
				roleVO.setName(b.getName());
				roleVO.setRoleId(b.getRoleId());
				if (b.getRoleId().equals(roleId)) {
					roleVO.setFlag((byte) 1);
				}
				ownRoleList.add(roleVO);
			}
		});
		model.addAttribute("list", ownRoleList);
		return request.getAttribute("moblie") + "adminEdit";
	}

	//管理员的添加
	@MoblieUrl
	@RequestMapping("/managerAdd/index")
	public String managerAdd(Model model) {
		ManageUser user = UserContext.getUser();
		Integer roleId = user.getRoleId();
		Integer compId = user.getCompId();
		List<CompRoleVO> compList = new ArrayList<>();

		ManageRoles ownRole = manageRolesMapper.selectByPrimaryKey(roleId);
		String permissions = ownRole.getPermissions();
		List<String> ownPermissionList = Arrays.asList(permissions.split(","));

		List<ManageComp> list = manageCompMapper.getCompListBySelect(compId);
		Map<Integer, String> compMap = list.stream().collect(Collectors.toMap(ManageComp::getCompId, ManageComp::getCompName));

		List<ManageRoles> roleList = manageRolesMapper.getAllRolesByComId(compId);
		Map<Integer, List<ManageRoles>> rolesByCompIdMap = roleList.stream().collect(Collectors.groupingBy(ManageRoles::getCompId));
		List<Integer> compIds = rolesByCompIdMap.keySet().stream().collect(Collectors.toList());

		JSONArray array = new JSONArray();
		compIds.stream().forEach(a -> {
			JSONObject jo1 = new JSONObject();
			jo1.put("value", a);
			jo1.put("text", compMap.get(a));
			CompRoleVO compRoleVO = new CompRoleVO();
			List<NewRoleVO> rolesList = new ArrayList<>();
			compRoleVO.setCompId(a);
			compRoleVO.setCompName(compMap.get(a));
			List<ManageRoles> ManageRolesList = rolesByCompIdMap.get(a);
			JSONArray array1 = new JSONArray();
			ManageRolesList.stream().forEach(b -> {
				String otherPermissions = b.getPermissions();
				List<String> otherPermissionList = Arrays.asList(otherPermissions.split(","));
				if (ownPermissionList.containsAll(otherPermissionList)) {
					JSONObject jo2 = new JSONObject();
					jo2.put("value", b.getRoleId());
					jo2.put("text", b.getName());
					NewRoleVO newRoleVO = new NewRoleVO();
					newRoleVO.setRoleId(b.getRoleId());
					newRoleVO.setRoleName(b.getName());
					rolesList.add(newRoleVO);
					array1.add(jo2);
				}
			});
			jo1.put("children", array1);
			array.add(jo1);
			compRoleVO.setRoleList(rolesList);
			compList.add(compRoleVO);
		});

		model.addAttribute("compList", compList);
		model.addAttribute("McompList", array);
		return request.getAttribute("moblie") + "adminAdd";
	}

	//角色列表
	@MoblieUrl
	@RequestMapping("/role/index")
	public String role() {
		return request.getAttribute("moblie") + "roleList";
	}

	//角色的添加修改
	@MoblieUrl
	@RequestMapping("/roleAdd/index")
	public String roleAdd(Model model) {
		List<ManageComp> compList = new ArrayList<>();
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		List<ManageComp> list = manageCompMapper.getCompListBySelect(compId);
		list.stream().forEach(a -> {
			ManageComp manageComp = new ManageComp();
			manageComp.setCompName(a.getCompName());
			manageComp.setCompId(a.getCompId());
			compList.add(manageComp);
		});
		model.addAttribute("compList", compList);
		return request.getAttribute("moblie") + "roleAdd";
	}

	//角色的修改
	@MoblieUrl
	@RequestMapping("/roleEdit/index")
	public String roleEdit(Model model, Integer roleId) {
		model.addAttribute("roleId", roleId);
		return request.getAttribute("moblie") + "roleEdit";
	}

	@MoblieUrl
	@RequestMapping("/permission/index")
	public String permission() {
		return request.getAttribute("moblie") + "tree";
	}

	@MoblieUrl
	@RequestMapping("/userUpdate/index")
	public String userUpdate() {
		return request.getAttribute("moblie") + "userInfo";
	}

	@MoblieUrl
	@RequestMapping("/userPsw/index")
	public String userPsw() {
		return request.getAttribute("moblie") + "changePwd";
	}

	@MoblieUrl
	@RequestMapping("/FAQ/index")
	public String FAQ() {
		return request.getAttribute("moblie") + "FAQ";
	}

	@MoblieUrl
	@RequestMapping("/feedback/index")
	public String feedback() {
		return request.getAttribute("moblie") + "feedback";
	}

	@MoblieUrl
	@RequestMapping("/main/index")
	public String main(Model model) {
		List<DailyRecordVO> list = new ArrayList<>();
		List<DailyRecordVO> listBig = new ArrayList<>();
		List<DailyRecordVO> listMiddle = new ArrayList<>();
		List<DailyRecordVO> listLittle = new ArrayList<>();
		
		Date date = new Date();
		MyNumVO myNumVO = new MyNumVO();
		int allNum = 0;
		int max = 0;
		int maxBig = 0;
		int maxMiddle = 0;
		int maxLittle = 0;
		int errorNum = 1;
		int usedNum = 0;
		Integer compId = UserContext.getUser().getCompId();
		Byte useType = 0;
		List<ManageCase> listByCompId = manageCaseMapper.getListNumByCompId(compId, useType);
		List<String> caseNos = new ArrayList<>();
		for (ManageCase manageCase : listByCompId) {
			allNum += manageCase.getBoxSum();
			caseNos.add(manageCase.getCaseNo());
		}
		;
		myNumVO.setAllNum(allNum);


		if (!caseNos.isEmpty()) {

			ManageCaseBoxExample example = new ManageCaseBoxExample();
			example.setOrderByClause("DOOR_NUM");
			example.createCriteria().andCaseNoIn(caseNos).andIsDelEqualTo((byte) 0);
			List<ManageCaseBox> boxByCaseIds = manageCaseBoxMapper.selectByExample(example);
			List<ManageCaseBox> useList = boxByCaseIds.stream().filter(a -> a.getUseStatus() == 1).collect(Collectors.toList());
			List<ManageCaseBox> notIsConn = boxByCaseIds.stream().filter(a -> a.getIsConn() == 0).collect(Collectors.toList());
			usedNum = useList.size();
			errorNum = notIsConn.size();
			myNumVO.setUsedNum(useList.size());
			myNumVO.setErrorNum(notIsConn.size());

			double errorRate = 0;
			errorRate = (double) errorNum / (double) allNum * 100;
			DecimalFormat df = new DecimalFormat("######0.00");
			String errorRatestr = df.format(errorRate);

			double usageRate = (double) usedNum / (double) allNum * 100;
			DecimalFormat df1 = new DecimalFormat("######0.00");
			String usageRatestr = df1.format(usageRate);

			int unusedNum = allNum - usedNum;

			myNumVO.setErrorRate(errorRatestr);
			myNumVO.setUsageRate(usageRatestr);
			myNumVO.setUnusedNum(unusedNum);

			List<Integer> boxIdList = boxByCaseIds.stream().collect(Collectors.mapping(ManageCaseBox::getId, Collectors.toList()));
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.WEEK_OF_MONTH, -1);
			Date startTime = calendar.getTime();
			if (boxIdList != null && !boxIdList.isEmpty()) {


				AccessRecordExample accessRecordExample = new AccessRecordExample();
				accessRecordExample.createCriteria().andTypeEqualTo((byte) 1).andCreateTimeGreaterThan(startTime).andCreateTimeLessThan(date).andBoxIdIn(boxIdList);
				
				List<AccessRecord> all = accessRecordMapper.selectByExample(accessRecordExample);
				
				//
				Map<Integer, ManageCaseBox> mcbByBoxId = new HashMap<>();
				if(all!=null && !all.isEmpty()){
					//查询出记录中的boxid
					List<Integer> boxIds = all.stream().map(AccessRecord::getBoxId).collect(Collectors.toList());
					//去重boxid
					List<Integer> boxIdsDistinct = boxIds.stream().distinct().collect(Collectors.toList());
					ManageCaseBoxExample manageCaseBoxExample = new ManageCaseBoxExample();
					example.createCriteria().andIdIn(boxIdsDistinct).andIsDelEqualTo((byte) 0);
					List<ManageCaseBox> selectByExample = manageCaseBoxMapper.selectByExample(manageCaseBoxExample);
					mcbByBoxId = selectByExample.stream().collect(Collectors.toMap(ManageCaseBox::getId, v->v));
				}
				//
				Map<String, List<AccessRecord>> createDayMap = all.stream().collect(Collectors.groupingBy(AccessRecord::getCreateDay));
				for (int i = 0; i < 7; i++) {
					calendar.add(Calendar.DAY_OF_MONTH, 1);
					Date day = calendar.getTime();
					String formatDateTimetoString = DateTimeHelper.formatDateTimetoString(day, "yyyy-MM-dd");
					List<AccessRecord> accessRecordList = createDayMap.get(formatDateTimetoString);//当天的大中小柜所有记录
					
					Integer arAllCount = 0;
					Integer arBigCount = 0;
					Integer arMiddleCount = 0;
					Integer arLittleCount = 0;
					if (accessRecordList != null && !accessRecordList.isEmpty()) {
						for (int j = 0; j < accessRecordList.size(); j++) {
							AccessRecord ar = accessRecordList.get(j);
							if(mcbByBoxId.get(ar.getBoxId())==null){continue;}
							Byte size = mcbByBoxId.get(ar.getBoxId()).getSize();
							if(size == Byte.valueOf((byte)1)){
								arBigCount++;
							}else if(size == Byte.valueOf((byte)2)){
								arMiddleCount++;
							}else if(size == Byte.valueOf((byte)3)){
								arLittleCount++;
							}
						}
						arAllCount = accessRecordList.size();
					}
					list.add(new DailyRecordVO(arAllCount,formatDateTimetoString));//所有
					listBig.add(new DailyRecordVO(arBigCount,formatDateTimetoString));//大
					listMiddle.add(new DailyRecordVO(arMiddleCount,formatDateTimetoString));//中
					listLittle.add(new DailyRecordVO(arLittleCount,formatDateTimetoString));//小
					
					if (max < arAllCount) {
						max = arAllCount;
					}
					if(maxBig < arBigCount){
						maxBig = arBigCount;
					}
					if(maxMiddle < arMiddleCount){
						maxMiddle = arMiddleCount;
					}
					if(maxLittle < arLittleCount){
						maxLittle = arLittleCount;
					}
				}
				
				/*//大柜
				List<AccessRecord> allBig = accessRecordMapper.selectByExampleSize(accessRecordExample,1);
				CartogramUtil caru = new CartogramUtil(allBig,calendar);
				maxBig = caru.getMax();
				listBig = caru.getList();
				
				//中柜
				List<AccessRecord> allMiddle= accessRecordMapper.selectByExampleSize(accessRecordExample,2);
				CartogramUtil caruMiddle = new CartogramUtil(allMiddle,calendar);
				maxMiddle = caruMiddle.getMax();
				listMiddle = caruMiddle.getList();
				
				//小柜
				List<AccessRecord> allLittle= accessRecordMapper.selectByExampleSize(accessRecordExample,3);
				CartogramUtil caruLittle = new CartogramUtil(allLittle,calendar);
				maxLittle = caruLittle.getMax();
				listLittle = caruLittle.getList();*/
				
			}

		}
		
		model.addAttribute("max", max);
		model.addAttribute("num", myNumVO);
		model.addAttribute("list", list);
		
		model.addAttribute("maxBig", maxBig);
		model.addAttribute("listBig", listBig);
		model.addAttribute("maxMiddle", maxMiddle);
		model.addAttribute("listMiddle", listMiddle);
		model.addAttribute("maxLittle", maxLittle);
		model.addAttribute("listLittle", listLittle);
		return request.getAttribute("moblie") + "main";
	}

	@RequestMapping("/weixin/openCase/save")
	public String weixinSave(String CaseNo, Long Timestamp) {
		return "openSave";
	}

	@RequestMapping("/weixin/openCase/get")
	public String weixinGet(String CaseNo, Long Timestamp) {
		return "openGet";
	}

}
